import { FC, Suspense, lazy, useEffect } from 'react';
import { Route, Switch, RouteProps } from 'react-router';
import { Spin } from 'antd';
import routePath from '@/models/route';
import { getQueryString } from '@/utils/util';
import { login } from '@/api/login';

const Home = lazy(() => import('@/pages/Home/index'));
const NotFound = lazy(() => import('@/pages/NotFound/index'));
const NotVerify = lazy(() => import('@/pages/NotVerify/index'));

// 定义路由集合
const routes: RouteProps[] = [
  {
    path: routePath.HOME,
    exact: true,
    component: Home,
  },
  {
    path: routePath.NOT_VERIFY,
    exact: true,
    component: NotVerify,
  },
];

const env = process.env.NODE_ENV;

// 定义路由组件
const Routes: FC = () => {
  const token: string = getQueryString('token');
  // 调用登录接口
  const loginMethod = async () => {
    await login({ token })
      .then(({ code, data }) => {
        localStorage.setItem('tenant_code', data.tenant_code);
        localStorage.setItem('user_account', data.user_account);
        localStorage.setItem('user_group', data.user_group);
        (window as any).enResolve()
      })
      .catch((err) => {
        console.log(err);
        // 未登录时，直接跳转到登录页，登录完成后再跳回来
        location.href = `${location.origin}/login.shtml?ret_url=${encodeURIComponent(location.href)}`;
        // 登录失败时清掉本地缓存的 token
        localStorage.removeItem('token');
      });
  };

  useEffect(() => {
    env === 'development' ? (window as any).enResolve() : loginMethod();
  }, [])

  return (
    <Suspense fallback={
      <Spin size="large">
        <div></div>
      </Spin>
    }>
      <Switch>
        {routes.map((r, index) => {
          const { path, exact, component } = r;
          const LazyCom = component as any;
          return (
            <Route
              key={index}
              path={path}
              exact={exact}
              render={(props) => (
                <LazyCom {...props} />
              )}
            />
          );
        })}
        {/* 兜底的路由 */}
        <Route component={NotFound} />
      </Switch>
    </Suspense>
  );
};

export default Routes;
